﻿using AutoMapper;
using B.Rabbit.DataBase.Domain;
using B.Rabbit.DataBase.ErrorCode;
using B.Rabbit.DataBase.Infrastructure.Infrastructure;
using B.Rabbit.DataBase.Read.Api.Applocation.Command.Rabbit.Breeding;
using MediatR;
using Yitter.IdGenerator;

namespace B.Rabbit.DataBase.Read.Api.Applocation.Handler.Rabbit.Breeding
{
    public class AddBreedingCommandHandler : IRequestHandler<AddBreedingCommand, ApiResult<int>>
    {
        IBaseRepository<BreedingModel> breedingmodel;
        IMapper mapper;

        public AddBreedingCommandHandler(IBaseRepository<BreedingModel> breedingmodel, IMapper mapper)
        {
            this.breedingmodel = breedingmodel;
            this.mapper = mapper;
        }
        /// <summary>
        /// 养殖信息添加
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<ApiResult<int>> Handle(AddBreedingCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var entity = mapper.Map<BreedingModel>(request);
            entity.Id = YitIdHelper.NextId();
            var r = await breedingmodel.AddAsync(entity);
            if(r>0)
            {
                res.msg = "添加成功";
                res.data = r;
                res.code = StatusCode.Ok;
            }
            else
            {
                res.msg = "添加失败";
                res.data = r;
                res.code = StatusCode.Fail;
            }
            return res;
        }
    }
}
